<template>
  <div class="box">
    <!-- 有数据 -->
    <div v-show="videoState" class="hasData">
      <!-- 视话区 -->
      <Video-div
        :videoState="videoState"
        @changeVideoState="changeVideoState"
        @sendPatientData="sendPatientData"
      ></Video-div>
      <!-- 信息功能 -->
      <div class="infoDiv">
        <vue-scroll ref="vs" :ops="$store.state.ops">
          <!-- 结束 -->
          <span class="closeVideo colorGray" v-if="$store.state.common.STATE==6">结束问诊</span>
          <!-- 灰按钮 -->
          <div class="closeVideo" @click="closeVideo" v-else>结束问诊</div>
          <!-- 患者信息 -->
          <div class="patientDiv">
            <span class="titleBlod">患者资料</span>
            <span>
              <span class="patientTitle">就诊人：</span>
              <span class="margin08">{{patientData.patientName | patientName}}</span>
              <span class="margin08">{{patientData.patientSex | patientSex}}</span>
              <span class="margin08">{{patientData.patientAge | patientAge}}</span>
            </span>
            <span>
              <span class="patientTitle">是否就该病到医院就诊过：</span>
              <span class="margin08">{{patientData.firstQuery | checkState}}</span>
            </span>
            <span class="titleBlod">病情描述</span>
            <div class="patientDescription">{{patientIllnessDesc}}</div>
            <div class="patientImg">
              <viewer :images="patientData.imageList">
                <img class="imgItem" v-for="item in patientData.imageList" :src="item" :key="item" />
              </viewer>
            </div>
          </div>
        </vue-scroll>
        <!-- 操作 -->
        <div class="bottomBtn">
          <!-- V2.2.2舍弃
            <span class="btn colorGray" v-if="$store.state.common.STATE==6">填写病历</span>


            <span
              class="btn"
              @click="showModel('AddMedicalRecord')"
              v-else-if="!medicalHistoryId"
            >填写病历</span>
            <span class="btn" @click="showModel('CheckMedicalRecord')" v-else>查看病历</span>
            <span class="btn colorGray" v-if="$store.state.common.STATE==6">开处方</span>
            <span class="btn" @click="chackHasMedicalRecord" v-else-if="!recipeId">开处方</span>
            <span class="btn" @click="checkPrescription" v-else>查看处方</span> 
          -->
          <span class="btn btnL colorGray" v-if="$store.state.common.STATE==6">开处方</span>
          <span
            class="btn btnL"
            @click="modelTypeMedicalHistory = 'medicalHistoryDialog'"
            v-else-if="!recipeId||!medicalHistoryId"
          >开处方</span>
          <span
            class="btn btnS"
            @click="modelType = 'CheckMedicalRecord'"
            v-if="medicalHistoryId"
          >查看病历</span>
          <span class="btn btnS" @click="checkPrescription" v-if="recipeId">查看处方</span>
        </div>
      </div>
    </div>
    <!-- 无数据 -->
    <div v-show="!videoState" class="noData">
      <img class="noPatientImg" src="/static/img/暂无数据.png" alt />
      <span
        class="noPatient"
        v-if="$store.state.common.STATE==1||$store.state.common.STATE==3 || $store.state.common.STATE==6"
      >暂无患者问诊，请耐心等待…</span>
      <span class="noPatient" v-if="$store.state.common.STATE==2">点击开始接单按钮，开始接诊患者</span>
    </div>
    <!-- 弹出框  V2.2.2舍弃 -->
    <!-- 填写病历弹框 -->
    <AddMedicalRecord
      :showTrue="modelType==='AddMedicalRecord'"
      :patientData="patientData"
      @close="closeModel"
      @submit="submitMedicalRecord"
    ></AddMedicalRecord>
    <!-- 开处方弹框 -->
    <AddPrescription
      :showTrue="modelType==='AddPrescription'"
      :clearData="clearPrescriptionData"
      @close="closeModel"
      @submit="savePrescription"
    ></AddPrescription>

    <!-- 弹出框  V2.2.2使用 -->
    <!-- 查看病历弹框 -->
    <CheckMedicalRecord
      :showTrue="modelType==='CheckMedicalRecord'"
      :patientData="medicalHistoryData"
      @close="modelType = ''"
    ></CheckMedicalRecord>
    <!-- 提交处方弹框 -->
    <submitPrescriptiony
      :showTrue="modelType==='submitPrescription'"
      :prescriptionData="prescriptionData"
      :reviewShow="submitBtn"
      @close="closeModel"
      @change="changePrescription"
      @submit="submitPrescription"
    ></submitPrescriptiony>
    <!-- 填写处方弹框 -->
    <medicalHistoryDialog
      :showTrue="modelTypeMedicalHistory==='medicalHistoryDialog'"
      :patientData="patientData"
      @close="closeMedicalHistoryModel"
      @submit="savePrescription"
    ></medicalHistoryDialog>
  </div>
</template>

<script>
import VideoDiv from "./videoComponent";
import AddMedicalRecord from "../../components/dialog/medicalRecord";
import CheckMedicalRecord from "../../components/dialog/checkMedicalRecord";
import AddPrescription from "../../components/dialog/prescriptionDialog";
import submitPrescriptiony from "../../components/dialog/depengingDialog";
import medicalHistoryDialog from "../../components/dialog/medicalHistoryDialog";
import { addRecipeMedicalHistory } from "../../requestApi/prescription";
import {
  getOrderInfoAPP,
  getOrderInfo,
  doctorStartOrder,
  doctorEndOrder,
  addMedicalHistory,
  getlastOrder,
  queryMedicalHistory
} from "../../requestApi/incompleteCommunication";
export default {
  components: {
    VideoDiv,
    AddMedicalRecord,
    CheckMedicalRecord,
    AddPrescription,
    submitPrescriptiony,
    medicalHistoryDialog
  },
  data() {
    return {
      videoState: false, // 视话状态
      submitBtn: true, // 显示处方弹出框底部按钮
      modelType: "", // 弹框类型
      modelTypeMedicalHistory: "", //添加病历处方弹框
      firstDiagnose: "", // 初步诊断
      medicalHistoryId: "", // 病历ID
      medicalHistoryData: {}, // 病历信息
      recipeId: "", // 处方ID
      patientData: {}, // 订单信息
      doctorData: {}, // 医生信息
      prescriptionData: {}, // 处方信息
      patientIllnessDesc: "",
      clearPrescriptionData: true,
      // 是否关闭添加病例处方
      isModelTypeMedicalHistory: false
    };
  },
  filters: {
    checkState: function(val) {
      return val ? "是 " : "否";
    },
    patientName: function(val) {
      return val ? val : "未知";
    },
    patientSex: function(val) {
      var data = "";
      if (val == 0) {
        data = "女";
      } else if (val == 1) {
        data = "男";
      } else {
        data = "未知";
      }
      return data;
    },
    patientAge: function(val) {
      return val ? val + "岁" : "未知";
    }
  },
  created() {
    let self = this;

    sessionStorage.removeItem("LastOrder");
    if (
      sessionStorage.getItem("videoData") &&
      sessionStorage.getItem("EndOfConsultationOrNot") == "true"
    ) {
      self.videoState = true;
    }
    if (localStorage.getItem("doctorId")) {
      self.doctorData.doctorId = localStorage.getItem("doctorId");
      self.doctorData.doctorName = localStorage.getItem("doctorName");
    }
    this.clearData();
  },
  mounted() {
    let self = this;
    self.$bus.$on("saveUser", self.saveUser);
    this.toGetLastOrder();
  },
  watch: {
    "$store.state.common.STATE": function(val) {
      if (val === 4) {
        this.toChangeOrderStates();
      }
      console.log("common.STATE", val);
    }
  },
  methods: {
    // 查询医生最后一条在问诊中的订单
    toGetLastOrder() {
      let self = this;
      let response = getlastOrder({
        doctorId: self.doctorData.doctorId
      }).then(response => {
        if (response.code == 200) {
          if (response.data && response.data.orderId) {
            self.videoState = true;
            self.$bus.$emit("LastOrder");
            self.patientData = response.data;
            self.patientData.imageList = response.data.illnessImage
              ? response.data.illnessImage.split(",")
              : [];
            self.medicalHistoryId = response.data.medicalHistoryId;
            self.recipeId = response.data.recipeId;
            self.patientIllnessDesc = response.data.illnessDesc;
            if (response.data.medicalHistoryId) {
              self.getMedicalRecordData(response.data.medicalHistoryId);
            }
          } else {
            sessionStorage.removeItem("videoData");
            sessionStorage.removeItem("formUser");
            sessionStorage.removeItem("EndOfConsultationOrNot");
          }
        }
      });
    },
    // 视话状态
    changeVideoState(val) {
      let self = this;
      self.videoState = val;
    },
    // 获取订单信息
    sendPatientData(val) {
      let self = this;
      if (val.version == 4) {
        //APP
        let response = getOrderInfoAPP({
          doctorId: self.doctorData.doctorId,
          userId: val.id
        })
          .then(response => {
            if (response.code == 200 && response.data) {
              if (response.data.orderId) {
                self.$bus.$emit("displayVideoBox", val.id);
              }
              self.patientData = response.data;
              self.patientData.imageList = response.data.illnessImage
                ? response.data.illnessImage.split(",")
                : [];
              self.medicalHistoryId = response.data.medicalHistoryId;
              self.recipeId = response.data.recipeId;
              self.patientIllnessDesc = response.data.illnessDesc;
            } else {
              this.$message({
                type: "error",
                message: "暂无数据！"
              });
            }
          })
          .catch(msg => {
            this.$message({
              type: "error",
              message: msg
            });
          });
      } else {
        //一体机
        let response = getOrderInfo({
          doctorId: self.doctorData.doctorId,
          deviceId: val.id,
          factoryId: val.factoryId
        })
          .then(response => {
            if (response.code == 200 && response.data) {
              if (response.data.orderId) {
                self.$bus.$emit("displayVideoBox", val.id);
              }
              self.patientData = response.data;
              self.patientData.imageList = [];
              self.medicalHistoryId = response.data.medicalHistoryId;
              self.recipeId = response.data.recipeId;
            } else {
              this.$message({
                type: "error",
                message: "暂无数据！"
              });
            }
          })
          .catch(msg => {
            this.$message({
              type: "error",
              message: msg
            });
          });
      }
    },
    // 开始接诊
    toChangeOrderStates() {
      let self = this;
      let response = doctorStartOrder({
        orderId: self.patientData.orderId
      })
        .then(res => {
          if (res.code == 200) {
          } else {
            self.$message({
              type: "error",
              message: res.message
            });
          }
        })
        .catch(msg => {
          self.$message({
            type: "error",
            message: res.message
          });
        });
    },
    // 结束接诊
    closeVideo() {
      let self = this;
      const baseConfirm = this.$baseConfirm({
        show: false,
        title: "确认结束此次问诊？",
        text: ``,
        confirmButton: {
          text: "确定",
          ontap: function() {
            baseConfirm.close().then(function(res) {
              let response = doctorEndOrder({
                doctorId: self.doctorData.doctorId,
                orderId: self.patientData.orderId
              })
                .then(response => {
                  if (response.code == 200) {
                    sessionStorage.removeItem("videoData");
                    sessionStorage.removeItem("formUser");
                    sessionStorage.removeItem("EndOfConsultationOrNot");
                    self.clearData();
                    self.videoState = false;
                    self.$store.dispatch("GET_STATE", 3);
                  } else {
                    self.$message({
                      type: "error",
                      message: response.message
                    });
                  }
                })
                .catch(msg => {
                  self.$message({
                    type: "error",
                    message: "结束问诊失败"
                  });
                });
            });
          }
        },
        cancelButton: {
          text: "取消"
        }
      });
    },
    // 关闭弹框
    closeModel() {
      this.modelType = "";
      if (this.isModelTypeMedicalHistory) {
        this.modelTypeMedicalHistory = "";
      }
    },
    closeMedicalHistoryModel() {
      this.modelTypeMedicalHistory = "";
    },
    // 完成处方病历填写---打开提交页
    savePrescription(val) {
      let self = this;
      var userInfo = {
        orderId: this.patientData.orderId,
        patientId: this.patientData.patientId,
        userId: this.patientData.userId,
        // createTime: this.patientData.orderTime,
        createTime: new Date().getTime(),
        name: this.patientData.patientName,
        sex: this.patientData.patientSex,
        age: this.patientData.patientAge,
        recipeType: 0, // 处方类型: 0普通处方, 1其他
        recipeSource: 0, // 处方来源:0=web端,1=一体机,
        doctorId: this.doctorData.doctorId,
        doctorName: this.doctorData.doctorName,
        drugstoreId: this.patientData.sourceShop, //购药门店id
        illnessDesc: val.illnessDesc, // 病情描述
        firstDiagnose: val.firstDiagnose, // 初步诊断
        treatmentSuggestion: val.treatmentSuggestion //处理意见
      };
      this.prescriptionData = { drugList: val.drugList, userInfo: userInfo };
      this.isModelTypeMedicalHistory = true;
      this.modelType = "submitPrescription";
    },
    // 重新编辑处方病历---打开填写页
    changePrescription() {
      this.isModelTypeMedicalHistory = false;
      this.modelType = "";
      this.clearPrescriptionData = false;
    },
    // 提交处方病历
    submitPrescription(val) {
      let self = this;
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      let response = addRecipeMedicalHistory({
        ...this.prescriptionData.userInfo,
        drugList: this.prescriptionData.drugList
      })
        .then(response => {
          loading.close();
          if (response.code == 200) {
            self.recipeId = response.data.recipeId;
            self.medicalHistoryId = response.data.medicalHistoryId;
            self.clearPrescriptionData = true;
            self.isModelTypeMedicalHistory = true;
            self.closeModel();
            self.getMedicalRecordData(response.data.medicalHistoryId);
          } else {
            self.$message({
              type: "error",
              message: response.message
            });
          }
        })
        .catch(msg => {
          loading.close();
          self.$message({
            type: "error",
            message: "系统出小差！"
          });
        });
    },

    // 打开弹框 V2.2.2舍弃
    showModel(val) {
      this.modelType = val;
      if (val === "CheckMedicalRecord") {
        this.checkMedicalRecord();
      }
    },
    // 开处方判断病历 V2.2.2舍弃
    chackHasMedicalRecord() {
      if (this.firstDiagnose) {
        this.showModel("AddPrescription");
      } else {
        this.$message({
          type: "error",
          message: "请先填写病历"
        });
      }
    },
    // 提交信息---添加病历 V2.2.2舍弃
    submitMedicalRecord(val, type) {
      let self = this;
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      self.medicalHistoryId = "";
      let response = addMedicalHistory({
        userId: val.userId,
        patientId: val.patientId,
        doctorId: val.doctorId,
        illnessDesc: val.illnessDesc,
        firstDiagnose: val.firstDiagnose,
        treatmentSuggestion: val.treatmentSuggestion,
        orderId: val.orderId
      })
        .then(response => {
          loading.close();
          if (response.code == 200) {
            if (type == "recip") {
              //打开处方页
              self.modelType = "AddPrescription";
            } else {
              self.closeModel();
            }
            self.firstDiagnose = val.firstDiagnose;
            self.medicalHistoryId = response.data.medicalHistoryId;
            self.patientData = val;
          } else {
            self.$message({
              type: "error",
              message: response.message
            });
          }
        })
        .catch(msg => {
          loading.close();
          self.$message({
            type: "error",
            message: "系统出小差！"
          });
        });
    },
    // 查看病历
    getMedicalRecordData(val) {
      let self = this;
      let response = queryMedicalHistory({
        medicalHistoryId: val
      })
        .then(response => {
          if (response.code == 200) {
            self.medicalHistoryData = response.data;
            // self.patientData.firstDiagnose = response.data.firstDiagnose;
            // self.patientData.treatmentSuggestion =
            //   response.data.treatmentSuggestion;
            // self.firstDiagnose = response.data.firstDiagnose;
          } else {
            self.$message({
              type: "error",
              message: response.message
            });
          }
        })
        .catch(msg => {
          self.$message({
            type: "error",
            message: "系统出小差！"
          });
        });
    },
    // 跳转页面---查看处方
    checkPrescription() {
      // 查询最后一个问诊中订单获取最新处方id
      let self = this;
      let response = getlastOrder({
        doctorId: self.doctorData.doctorId
      }).then(response => {
        if (response.code == 200) {
          self.$router.push({
            path: "/home/prescription/content",
            query: {
              recipeId: response.data.recipeId
            }
          });
        }
      });
      // var routerUrl = "/home/prescription/content?recipeId=" + this.recipeId;
      // this.$router.push(routerUrl);
    },
    // 异常挂断存数据
    saveUser() {
      sessionStorage.setItem("videoData", JSON.stringify(this.patientData));
    },
    // 清除数据
    clearData() {
      let self = this;
      self.firstDiagnose = ""; // 初步诊断
      self.medicalHistoryId = ""; // 病历ID
      self.recipeId = ""; // 处方ID
      self.prescriptionData = {}; // 处方信息
      self.patientData = {}; // 患者信息
      self.patientIllnessDesc = ""; //病情描述
      self.clearPrescriptionData = true;
    }
  }
};
</script>

<style scoped>
.showModal {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
  position: fixed;
  top: 0;
  right: 0;
  z-index: 20010;
}
.modalMask {
  position: fixed;
  overflow: auto;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 2010;
  -webkit-overflow-scrolling: touch;
  outline: 0;
  background-color: rgba(0, 0, 0, 0.4);
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  user-select: none;
}
/* 主体 */
.box {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
/* 暂无数据 */
.noData {
  width: 100%;
  height: 100%;
  background: #ffffff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.noPatientImg {
  width: 200px;
  height: 200px;
}
.noPatient {
  font-size: 14px;
  font-family: MicrosoftYaHei;
  color: rgba(102, 102, 102, 1);
  margin-top: 16px;
}
/* 有数据 */
.hasData {
  font-family: PingFangSC-Medium, PingFang SC;
  font-size: 14px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  overflow: hidden;
  height: 100%;
}
/* 视频 */
.videoDiv {
  width: 735px;
  height: calc(100vh - 100px);
  background: rgba(32, 32, 32, 1);
  border-radius: 6px;
}
/* 信息 */
.infoDiv {
  margin-left: 20px;
  height: calc(100vh - 100px);
  width: 740px;
  overflow: hidden;
  background: #ffffff;
  border-radius: 6px;
  color: rgba(55, 55, 55, 1);
  position: relative;
}
/* 结束问诊 */
.closeVideo {
  position: absolute;
  top: 24px;
  right: 40px;
  width: 150px;
  line-height: 40px;
  background: rgba(42, 41, 40, 1);
  border-radius: 20px;
  font-family: MicrosoftYaHei;
  color: rgba(255, 255, 255, 1);
  text-align: center;
}
/* 患者详情 */
.patientDiv {
  padding: 0;
  padding-left: 40px;
  display: flex;
  flex-direction: column;
}
.titleBlod {
  margin: 24px 0 16px 0;
  font-size: 16px;
  font-weight: bold;
  color: rgba(42, 41, 40, 1);
  line-height: 22px;
}
.patientTitle {
  font-weight: 400;
  color: rgba(122, 118, 118, 1);
  line-height: 32px;
}
.patientDescription {
  margin-right: 40px;
  word-wrap: break-word;
  font-weight: 400;
  color: rgba(55, 55, 55, 1);
  line-height: 20px;
}
.patientImg {
  margin-top: 10px;
  margin-bottom: 120px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}
.imgItem {
  width: 132px;
  height: 132px;
  border-radius: 6px;
  margin: 12px 12px 0 0;
}
/* 按钮 */
.bottomBtn {
  width: 100%;
  display: flex;
  justify-content: center;
  position: absolute;
  bottom: 0;
  background-color: #ffffff;
}
.btn {
  display: inline-block;
  line-height: 40px;
  background: rgba(255, 101, 50, 1);
  border-radius: 20px;
  font-family: MicrosoftYaHei;
  color: rgba(255, 255, 255, 1);
  text-align: center;
  margin: 15px 15px 70px 15px;
}
.btnS {
  width: 150px;
}
.btnL {
  width: 326px;
}
.colorGray {
  background: #cccccc;
}
.margin08 {
  margin: 0 8px;
}
</style>
